/*
 * Copyright 2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.meruvian.yama.social.signup;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import javax.validation.Valid;

import org.apache.commons.codec.digest.DigestUtils;
import org.meruvian.yama.entity.Item;
import org.meruvian.yama.entity.Person;
import org.meruvian.yama.entity.User;
import org.meruvian.yama.form.ItemForm;
import org.meruvian.yama.form.PersonForm;
import org.meruvian.yama.form.UserForm;
import org.meruvian.yama.message.Message;
import org.meruvian.yama.message.MessageType;
import org.meruvian.yama.service.PersonService;
import org.meruvian.yama.service.UserService;
import org.meruvian.yama.social.signin.SignInUtils;
import org.meruvian.yama.validator.ItemValidator;
import org.meruvian.yama.validator.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

@Controller
public class SignupController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private PersonService personService;


//	@RequestMapping(value="/signup", method=RequestMethod.GET)
//	public SignupForm signupForm(WebRequest request) {
//		Connection<?> connection = ProviderSignInUtils.getConnection(request);
//		if (connection != null) {
//			request.setAttribute("message", new Message(MessageType.INFO, "Your " + StringUtils.capitalize(connection.getKey().getProviderId()) + " account is not associated with a Meruvian Yama account. If you're new, please sign up."), WebRequest.SCOPE_REQUEST);
//			return SignupForm.fromProviderUser(connection.fetchUserProfile());
//		} else {
//			return new SignupForm();
//		}
//	}
	
	@RequestMapping(value = "/signup", method = RequestMethod.GET)
	public ModelAndView signup(HttpServletRequest request, HttpServletResponse response, WebRequest webRequest) throws Exception {
		Connection<?> connection = ProviderSignInUtils.getConnection(webRequest);
		ModelAndView mv = new ModelAndView();
		if (connection != null) {
			webRequest.setAttribute("message", new Message(MessageType.INFO, "Your " + StringUtils.capitalize(connection.getKey().getProviderId()) + " account is not associated with a Spring Social Showcase account. If you're new, please sign up."), WebRequest.SCOPE_REQUEST);
			mv.addObject("user", SignupForm.fromProviderUser(connection.fetchUserProfile()));
			mv.addObject("person", new Person());
			mv.setViewName("signup/signup");
			return mv;
		}else{
		mv.addObject("user", new User());
		mv.addObject("person", new Person());
		mv.setViewName("signup/signup");
		return mv;
		}
	}
    
	@RequestMapping(value="/signup", method=RequestMethod.POST)
	public ModelAndView signup(HttpServletRequest request, WebRequest webRequest, @RequestParam("password") String password, @ModelAttribute("user") UserForm user, BindingResult bindingResult) {
		new UserValidator().validate(user, bindingResult);
		if(bindingResult.hasErrors()){
			ModelAndView mv = new ModelAndView();
			mv.addObject("user", new User());
			mv.setViewName("signup/signup");
			return mv;
		}else{
			Person person = user.getPerson(); 
//	    	person.setGender(Boolean.parseBoolean(gender));
			user.setPassword(DigestUtils.md5Hex(user.getPassword().getBytes()));

//			SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
//			Date birthdate = new Date();
//
//			try {
//				birthdate = format.parse(birthDate);
//			} catch (ParseException e) {
//				e.printStackTrace();
//			}

//			person.setBirthDate(birthdate);
//			JOptionPane.showMessageDialog(null, user.getUsername()+"  "+user.getUser().getUsername());
			personService.save(person);
			user.setPerson(person);
			userService.save(user.getUser());
//			JOptionPane.showMessageDialog(null, user.getUser().getId());
			
			User userTemp = user.getUser();
			if (userTemp != null) {
//				JOptionPane.showMessageDialog(null, "oi");
				SignInUtils.signin(userTemp.getUsername());
				ProviderSignInUtils.handlePostSignUp(userTemp.getUsername(), webRequest);
				return new ModelAndView(new RedirectView(request.getContextPath()+"/"));
			}
			return null;
//			return new ModelAndView(new RedirectView(request.getContextPath()+"/signin"));
		}
			
		
		
		
		
//		if (user != null) {
//			SignInUtils.signin(user.getUsername());
//			ProviderSignInUtils.handlePostSignUp(user.getUsername(), webrequest);
//			return mv;
//		}
	}

	// internal helpers
	
//	private User createUser(SignupForm form, BindingResult formBinding) {
//		try {
//			User account = new User(form.getUsername(), form.getPassword(), form.getFirstName(), form.getLastName());
//			accountRepository.createAccount(account);
//			return account;
//		} catch (UsernameAlreadyInUseException e) {
//			formBinding.rejectValue("username", "user.duplicateUsername", "already in use");
//			return null;
//		}
//	}

}
